package br.ufal.tci.nexos.arcolive.service.connection.command;

import br.ufal.tci.nexos.arcolive.command.ArCoLIVEClientCommand;
import br.ufal.tci.nexos.arcolive.command.ArCoLIVECommandResult;
import br.ufal.tci.nexos.arcolive.exception.ArCoLIVECannotAddParticipantInGroupException;
import br.ufal.tci.nexos.arcolive.participant.ArCoLIVEParticipant;
import br.ufal.tci.nexos.arcolive.protocol.ArCoLIVEConnectionProtocol;
import br.ufal.tci.nexos.arcolive.service.broker.ArCoLIVEServiceBroker;
import br.ufal.tci.nexos.arcolive.service.connection.ConnectionRequest;

public class ReceiveConnectionCommand extends ArCoLIVEClientCommand {
    
	public ReceiveConnectionCommand(ConnectionRequest request) {
		super(request);
	}
	
	public ArCoLIVECommandResult executeImpl() {
		ArCoLIVEParticipant participant = (ArCoLIVEParticipant) this.request.getOwner();
		String response = "";
		
		try {

			ArCoLIVEServiceBroker serviceBroker = ArCoLIVEServiceBroker.getInstance();
			serviceBroker.getParticipantGroup().addParticipant(participant);
			participant.addListener(serviceBroker);			
			response = "1#commandId=" + ArCoLIVEConnectionProtocol.CONNECTED;
			
		} catch (ArCoLIVECannotAddParticipantInGroupException e) {
			
			response = "0#commandId=" + ArCoLIVEConnectionProtocol.NOT_CONNECTED;
			participant.getConnectionService().stopService();
			return new ArCoLIVECommandResult(this, response, e);
			
		}
		
		return new ArCoLIVECommandResult(this, response);
	}

}